import axios from 'axios'
import { message } from 'ant-design-vue'
import router from './router'

const request = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  withCredentials: true,
})

// 请求拦截
request.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截
request.interceptors.response.use(
  (resp) => {
    const { data } = resp
    if (data.code === 200) {
      return data
    } else if (data.code === 40100) {
      message.warning('请先登录')
      router.push('/user/login')
      return Promise.reject(new Error('请先登录'))
    } else if (data.code >= 40000 && data.code <= 50000) {
      message.error(data.msg)
      return Promise.reject(new Error(data.msg))
    }
    return resp
  },
  (error) => {
    if ('ERR_NETWORK' === error.code) {
      // 后端接口不通
      message.error('接口不通')
    }
    return Promise.reject(error)
  },
)

export default request
